import Vue from "vue";
import Vuex from "vuex";
import product from "./product/product";
import car from "./car/car"
//引入持久化库
import createPersistedState from "vuex-persistedstate";
Vue.use(Vuex);

export default new Vuex.Store({
  //组件需要被其他组件共享的数据
  /**
   * @如何访问state的数据
   * this.$store.state
   * 辅助函数引入到computed
   * 
   */
  //警告开发者要正确使用vuex
  // strict:true,
  state: {
       name:"你以为你接受的是谁的爱？是一个鸡神的爱",
       reverse:"此内容会反转",
       num:3,
       dataC:[]
  },
  //相当于vuex的计算属性
  getters: {
    //这个会接受一个参数
    reverse(state){
       return  state.reverse.split("").reverse().join("")
    }
  },
  //修改state的方式
  mutations: {
    //翻译过来就是变跟
    //通过this.$store.commit()
    //调试工具会没用
     INCREASE(state,payload){
      state.num++;
      console.log(payload)
    },
     DECREASE(state,payload){
       state.num--
    //    payload.target.onmouseover= function(){
    //        console.log("进来了")
    //    }
    //    payload.target.onmouseout= function(){
    //     console.log("移除了")
    // }
       if(state.num<=0) return state.num=0
    },
    SETDATA(state,payload){
         state.dataC = payload
    }
  },
  //处理异步请求
  //可以提交mutations
  actions: {
    //怎么触发action？？？
    //this.$store.dispath
    commit(context){
      console.log(context);
      fetch("http://chst.vip/data/index.json")
      .then(res =>res.json())
      .then(res=>{
        // console.log(res.data);
         context.commit("SETDATA",res.data)
      })
    }
  },
  //store模块化
  modules: {
    product,
    car
  },
  plugins:[
    //vuex是基于内存进行储存的,刷新之后会丢失
    createPersistedState({
       storage:window.sessionStorage,
       key:"jishen",
       paths:["name","product.products"]
    })
  ]
});
